package com.exercise.AndroidCamera;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
/*
기능 : 댓글 달기 기능 
작성 : 하드캔
완료일 : 2014.09.26 
	*/
public class CommentAdapter extends BaseAdapter{
	
	private Context context;
	private int layoutId, commnetCount;
	private ArrayList<String> user, comment, id;
	private LayoutInflater inflater;
	private String userID;
	private String comment_id;
	
	public CommentAdapter(Context context, int layoutId, ArrayList<String> user, ArrayList<String> comment, ArrayList<String> id, int commentCount, String userID) {
		// TODO Auto-generated constructor stub
		this.context = context;
		this.layoutId = layoutId;
		this.user = user;
		this.comment = comment;
		this.id = id;
		this.commnetCount = commentCount;
		this.userID = userID;
		inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return user.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		if(convertView == null){
			convertView = inflater.inflate(layoutId, parent, false);
		}
		
		TextView user_id = (TextView)convertView.findViewById(R.id.user);
		user_id.setText(user.get(position));
		
		TextView comments = (TextView)convertView.findViewById(R.id.comment);
		comments.setText(comment.get(position));
		
		Button delete = (Button)convertView.findViewById(R.id.btndelete);
		if(!delete.equals(null)){
			delete.setText("X");
			delete.setTag(position);
		}
		
		if(userID.equals(user_id.getText().toString())){
			delete.setVisibility(View.VISIBLE);
			delete.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					comment_id = id.get(position);
					CommentDeleteAsync deleteAsync = new CommentDeleteAsync();
					deleteAsync.execute();
					
					user.clear();
					comment.clear();
					id.clear();
					
					
					ReadPostActivity readPost = (ReadPostActivity) context;
					readPost.c_userArray = user;
					readPost.c_commentArray = comment;
					readPost.c_idArray = id;
					readPost.flag=1;
					readPost.onResume();

				}
			});
		}
		
		return convertView;
	}
	
	protected String[] delete_post(Context context, String comment_id){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/delete_comment.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(150000);	
       		conn.setReadTimeout(150000);
       		conn.setDefaultUseCaches(false); 
           	conn.setDoInput(true); 
           	conn.setDoOutput(true);  
           	conn.setRequestMethod("POST");
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
           	
         	StringBuffer buffer = new StringBuffer();
         	buffer.append("comment_id").append("=").append(comment_id);

			Log.d("c_idArray", comment_id);
			


            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
            
           InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
           br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();
           	
           	pString =  builder.toString();
           	Log.d("pString in read post", pString);
           	
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
       return result;
	}
	
	public class CommentDeleteAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			delete_post(context, comment_id);
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			
					
			super.onPostExecute(result);
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}
}
